package com.atguigu.tx.service.impl;

import com.atguigu.tx.service.api.StudentService;
import com.atguigu.tx.dao.api.StudentDao;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileNotFoundException;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true)
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentDao studentDao;

    @Transactional(readOnly = false, timeout = 3, rollbackFor = Exception.class, noRollbackFor = FileNotFoundException.class)
    public void multiUpdate() throws FileNotFoundException {
        System.out.println("----------Service 方法开始执行----------");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        String stuName01 = "王五~~~~~~~";
        String stuId01 = "3";
        studentDao.updateStuName(stuName01, stuId01);

        String stuAge02 = "100";
        String stuId02 = "4";
        studentDao.updateStuAge(stuAge02, stuId02);

        throw new FileNotFoundException("我们人为制造的异常~~~");
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void readStuName() {
        String stuId = "3";
        String stuName = studentDao.selectStuName(stuId);
        System.out.println("stuName = " + stuName);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void writeStuName() {
        String stuId = "3";
        String stuName = "大猪猪~~~";
        studentDao.updateStuName(stuName, stuId);
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    @Override
    public void writeStuAge() {
        String stuId = "4";
        String stuAge = "111";
        studentDao.updateStuAge(stuAge, stuId);
    }

}
